﻿#include"stdafx.h"
#include"SQLexpression.h"

bool SqlEx::ForInsert() {
	string db = CStringTostring(pSocket->cur_db);
	if (db == "") {
		pSocket->SendMSG("Please choose a database !");
		return 0;
	}
	int pos1 = Ex.find("into ");
	int pos2 = Ex.find("(");
	string tname = trimAll(Ex.substr(pos1 + 5, pos2 - pos1 - 5), " ");
	if (tname == "") {
		pSocket->SendMSG("table name is invalid!");
		return false;
	}
	if (!authority->Auth_Judge(user_host, db, tname)) {
		pSocket->SendMSG("You do not have permission to insert into the table !");
		return false;
	}
	regex re1("(?<=insert into ).+?(?=\\()");
	regex re2("(?<=\\().+?(?=\\))");

	smatch sm;
	vector<string>temp;
	vector<string> keys;
	vector<string> values;
	string::const_iterator st = Ex.begin();
	string::const_iterator en = Ex.end();

	while (regex_search(st, en, sm, re2)) {
		temp.push_back(trimAll(sm.str(), " "));
		st = sm[0].second;
	}
	keys = split(temp[0], ",");
	values = split(temp[1], ",");
	if (keys.size() != values.size()) {
		pSocket->SendMSG("检查前后括号中语句是否匹配！！！");
		return false;
	}
	vector<insert_model> vec_insert;
	for (unsigned int i = 0; i < keys.size(); i++) {
		insert_model m;
		m.key = keys[i];
		m.value = values[i];
		vec_insert.push_back(m);
	}
	string msg;
	serverDB->Table_Insert(tname.c_str(), vec_insert, db, msg);
	pSocket->SendMSG(msg);
	return true;
}